<template>
  <PageContainer v-model:enter-options="enterOptions">
    <Header :title="getPagesTitle" />

    <view class="pb-30">
      <StatusView :bo-status="data?.boStatus" :review-content="data?.reviewContent"></StatusView>
      <QuantityStatistics
        v-if="data?.id && data?.editAuth && [BoStatusEnum.Active,BoStatusEnum.Closed,BoStatusEnum.Expired,BoStatusEnum.Invalid].includes(data.boStatus!)"
        :id="data?.id"
        ref="quantityStatisticsRef"
      ></QuantityStatistics>
      <DetailsView :data="data" />
      <view v-if="data" class="mt-12">
        <PersonnelInfo
          :avatar="data.avatar"
          :company-name="data.companyName"
          :company-position="data.companyPosition"
          :user-name="data.userName"
          :member-level-name="data.memberLevelName"
          :org-name="data.orgName"
          :phone-number="data.phone"
        />
      </view>
      <view
        v-if="data&&[BoStatusEnum.Active,BoStatusEnum.Closed,BoStatusEnum.Expired,BoStatusEnum.Invalid].includes(data.boStatus!)"
        class="mt-12"
      >
        <SelectedAnswers
          :manage="data?.qaAuth"
          :id="data?.id"
          :is-valid="getBoIsValid"
          :bo-type="data.boType"
          :title="data.title"
        />
      </view>

      <TButtonGroup
        v-if="enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE && getBoIsValid"
        :show-background="true"
      >
        <template #header>
          <view class="disFlxAC mr-16" style="gap: 16rpx">
            <view v-if="data?.editAuth" class="disFlxCC w-50" @click="toEdit">
              <text class="ali-icon fz-24 mb-4">&#xe687;</text>
              <text class="fz-10">修改</text>
            </view>
            <view class="disFlxCC w-50" @click="handleBehaviorCollectOperate">
              <text v-if="data?.collect" class="ali-icon fz-24 mb-4" style="color: #2878ff">
                &#xe669;
              </text>
              <text v-else class="ali-icon fz-24 mb-4">&#xe664;</text>
              <text class="fz-10">收藏</text>
            </view>

            <view class="disFlxCC w-50" @click="handleShowSharePopup">
              <text class="ali-icon fz-24 mb-4">&#xe6ce;</text>
              <text class="fz-10">转发供需</text>
            </view>
          </view>
        </template>

        <TButton
          v-if="data?.editAuth"
          :text="`合作意向(${data?.cooperationNum || 0})`"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="toIntentionCooperation"
        />
        <template v-else>
          <TButton
            v-if="data?.userApplyRecordId"
            text="我的意向"
            type="primary"
            class="gutter-btn"
            custom-class="h-44 linh-44 br-22"
            @click="handleToIntentionDetails"
          />
          <TButton
            v-else
            text="我感兴趣"
            type="primary"
            class="gutter-btn"
            custom-class="h-44 linh-44 br-22"
            @click="handleApplyCooperation"
          />
        </template>
      </TButtonGroup>

      <!-- 失效/关闭 状态 -->
      <TButtonGroup
        v-else-if="
          (data?.boStatus === BoStatusEnum.Closed || data?.boStatus === BoStatusEnum.Expired) &&
          data?.editAuth
        "
        :show-background="true"
      >
        <TButton
          :text="`合作意向(${data?.cooperationNum || 0})`"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="toIntentionCooperation"
        />
      </TButtonGroup>
      <!-- 审核失败 -->
      <TButtonGroup
        v-else-if="data?.boStatus === BoStatusEnum.ReviewFailed && data?.editAuth"
        :show-background="true"
      >
        <TButton
          text="修改内容重新发布"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          :custom-style="{
            backgroundColor: '#F2F3F5',
            color: '#333',
          }"
          @click="toEdit"
        />
      </TButtonGroup>
      <!-- 草稿 -->
      <TButtonGroup
        v-else-if="data?.boStatus === BoStatusEnum.Draft && data?.editAuth"
        :show-background="true"
      >
        <TButton
          text="继续编辑"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="toEdit"
        />
      </TButtonGroup>
      <!-- 审核中 -->
      <TButtonGroup
        v-else-if="data?.boStatus === BoStatusEnum.Reviewing && data?.editAuth"
        :show-background="true"
      >
        <TButton
          text="邀请秘书处审核"
          type="none"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          :custom-style="{
            border: 'solid 1px #2878FF',
            color: '#2878FF',
          }"
          open-type="share"
          id="reviewing"
        />

        <TButton
          text="联系审核人"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="openPopup"
        ></TButton>
      </TButtonGroup>
    </view>
  </PageContainer>

  <CustomShare
    v-if="enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE && getBoIsValid"
    v-model:visible="showSharePopup"
    :disabled-on-share-app-message="true"
    @register="handleCustomShareregister"
  />
  <UniPopup ref="phoneCallPopup">
    <view class="phoneCall-info">
      <text class="title">联系审核人</text>
      <text class="desc">可通过以下电话联系供需审核人</text>
      <view class="phoneCall-info_item_box">
        <template v-for="v in reviewSysUserList" :key="v.id">
          <view class="phoneCall-info_item font-bold" @click="callPhone(v.phone)">
            <text>{{ v.userName }}</text>
            <text class="phoneCall-info_phone">
              {{ v.phone }}
            </text>
          </view>
        </template>
      </view>
      <view class="btn" @click="closePopup()">关闭</view>
    </view>
  </UniPopup>
  <PerfectInfoDialog />
  <!-- <ActionSheet
    v-model="showActionSheet"
    :itemList="actionSheetitemList"
    @change="handleActionSheetChange"
  ></ActionSheet> -->
</template>

<script lang="ts" setup>
  /* supplyDemandDetails 供需详情 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import DetailsView from '../components/DetailsView.vue';
  import PersonnelInfo from '../components/PersonnelInfo.vue';
  import SelectedAnswers from './components/SelectedAnswers.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { getUrl, navigateTo, onLoad } from '@/router';
  import { computed, getCurrentInstance, ref, watchEffect } from 'vue';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import {
    ApplicationTypeEnum,
    BoStatusEnum,
    BoTypeEnum,
    ReleaseTypeEnum,
  } from '@/enums/businessOpportunitiesEnum';
  import { getReviewSysUserList, supplyDemandDetails } from '@/api/businessOpportunities';
  import type {
    IReviewSysUserListResult,
    ISupplyDemandDetailsResult,
  } from '@/api/businessOpportunities/type';
  import { onPullDownRefresh, onShareAppMessage, onShareTimeline, onShow } from '@dcloudio/uni-app';
  import type { SupplyDemandDetails } from '@/router/types/modules';
  import { useAppShare } from '@/hooks/core/useAppShare';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { SceneValuesEnum } from '@/enums/sceneValuesEnum';
  import { addAppShareLog, behaviorCollectOperate, boUserPromotionCountDataAdd } from '@/api';
  import { getSupplyDemandPosterData, getSupplyDemandWxShareData } from '../components/utils';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import { BehaviorCollectTypeEnum, BusinessFunctionTypeEnum } from '@/enums/publicModuleEnum';
  import { useUserStore } from '@/store/modules/user';
  import QuantityStatistics from './components/QuantityStatistics.vue';
  import StatusView from './components/StatusView.vue';
  import PerfectInfoDialog from '@/components/PerfectInfoDialog/index.vue';

  const { userInfo } = useUserStore();
  const enterOptions = ref<UniApp.GetLaunchOptionsSyncOptions>();

  const { setWxSharePath, createShareQuery, setWxShareTimelineQuery } = useAppShare();

  /** 分享弹窗 */
  const showSharePopup = ref(false);

  const customShareLoading = ref(false);
  function handleCustomShareregister(e: any) {
    register(e);
    customShareLoading.value = true;
  }
  const reviewSysUserList = ref<IReviewSysUserListResult[]>([]);
  const _this = getCurrentInstance();
  const openPopup = (direction: string = 'center') => {
    (_this?.refs['phoneCallPopup'] as any).open(direction);
  };

  const closePopup = (direction: string = 'center') => {
    (_this?.refs['phoneCallPopup'] as any).close(direction);
  };

  /** 拨打电话 */
  function callPhone(phoneNumber: string) {
    uni.makePhoneCall({ phoneNumber });
  }

  const isToEdit = ref(false);
  const toEdit = () => {
    isToEdit.value = true;
    navigateTo({
      name: 'releaseBusinessOpportunities',
      options: {
        id: data.value?.id,
        releaseType: data?.value?.roleToAuth
          ? ReleaseTypeEnum.member
          : ReleaseTypeEnum.insteadMember,
      },
    });
  };
  const [
    register,
    {
      setWxShareOptions,
      setShareLogId,
      setPosterDrawData,
      setShareTimelineContent,
      setInternalLinkOptions,
      getCurrentWxShareOptions,
    },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      timeline: true,
      copyLink: true,
      insertOffiaccount: true,
      offiaccount: true,
    },
  });

  const data = ref<ISupplyDemandDetailsResult>();
  const loading = ref(true);

  const stopWatch = watchEffect(async () => {
    const v1 = customShareLoading.value;
    const v2 = data.value;
    if (!v1 || !v2) return;
    if (enterOptions.value?.scene === SceneValuesEnum.TIMELINE_SINGLEPAGE) return;
    await settingShareOptions();
    stopWatch();
  });

  let shareLogId: number;
  let codeImg: string;
  /** 设置分享参数 */
  async function settingShareOptions() {
    setInternalLinkOptions({
      name: 'supplyDemandDetails',
      options: { id: data.value!.id },
    });
    const path = setWxSharePath({
      name: 'supplyDemandDetails',
      options: { id: data.value!.id },
    });

    const routeQuery = createShareQuery({ id: data.value!.id });
    await setWxShareOptions([getSupplyDemandWxShareData(data.value!, path)]);
    if (!shareLogId) {
      const { id } = await addAppShareLog({
        path: getUrl('supplyDemandDetails'),
        query: JSON.stringify(routeQuery),
      });
      shareLogId = id;
    }
    setShareLogId(shareLogId);
    const shareTimelineContent = {
      query: setWxShareTimelineQuery(routeQuery),
      title: data.value?.title,
      imageUrl: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/bo-icon.jpg',
    };
    setShareTimelineContent(shareTimelineContent);

    if (!codeImg) codeImg = await createMiniCode({ shareLogId });
    const posterData = getSupplyDemandPosterData(data.value!, codeImg);
    await setPosterDrawData([posterData]);
  }

  function handleShowSharePopup() {
    if (data.value?.appUserInfoId !== userInfo.mainUserId) {
      boUserPromotionCountDataAdd({ type: BusinessFunctionTypeEnum.BO, dataId: data.value?.id! });
    }
    showSharePopup.value = true;
  }

  /** 判断供需是否有效 */
  const getBoIsValid = computed(() => {
    return data.value?.boStatus === BoStatusEnum.Active;
  });

  const routeOptions = ref<SupplyDemandDetails>();
  onLoad<'supplyDemandDetails'>((op) => {
    routeOptions.value = op;
    getData();
  });

  onShow(async () => {
    if (routeOptions.value && data.value) {
      await getData();
      routeOptions.value?.successFn?.();
      if (isToEdit.value) {
        /** 编辑页面会清空缓存图片, 要重新生成分享图 */
        settingShareOptions();
        isToEdit.value = false;
      }
    }
  });

  const getPagesTitle = computed(() => {
    if (!data.value) return '详情';
    return data.value.boType === BoTypeEnum.Demand ? '需求详情' : '供应详情';
  });

  async function getData() {
    loading.value = false;
    const res = await supplyDemandDetails({
      id: routeOptions.value?.id!,
      shareKey: routeOptions.value?.shareKey,
    });
    if (res.boStatus !== BoStatusEnum.Active) {
      wx.hideShareMenu({ menus: ['shareAppMessage', 'shareTimeline'] });
    }
    data.value = res;
    loading.value = false;
    uni.stopPullDownRefresh();

    if (res.boStatus === BoStatusEnum.Reviewing) {
      getReviewSysUserList({ reviewRecordId: res.reviewRecordId! }).then(
        (r) => (reviewSysUserList.value = r),
      );
    }
  }

  /** 意向详情 */
  function handleToIntentionDetails() {
    navigateTo({
      name: 'intentionDetails',
      options: {
        id: data.value?.userApplyRecordId!,
        type: 'send',
      },
    });
  }
  const quantityStatisticsRef = ref<InstanceType<typeof QuantityStatistics>>();
  function handleBehaviorCollectOperate() {
    behaviorCollectOperate({ type: BehaviorCollectTypeEnum.BO, dataId: data.value?.id! }).then(
      (bol) => {
        if (bol) {
          uni.showModal({
            title: '收藏提示',
            content:
              '您已收藏供需信息成功！可前往【我的】-【我的供需】-【我收藏的】查看已收藏的供需列表。',
            confirmText: '我知道了',
            showCancel: false,
          });
        }
        data.value!.collect = bol;
        quantityStatisticsRef.value?.queryBoCountInfo();
        routeOptions.value?.successFn?.();
      },
    );
  }

  onShareAppMessage((e) => {
    if (e.target?.id && data.value?.boStatus === BoStatusEnum.Reviewing) {
      return {
        title: `${userInfo.userName}正在申请供需发布，秘书处管理员快来帮我审核吧~`,
        path: setWxSharePath({
          name: 'businessOpportunitieAuditDetail',
          options: { id: data.value.reviewRecordId! },
        }),
        imageUrl:
          'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/Invitation-handling.png',
      };
    }
    return getCurrentWxShareOptions();
  });

  const toIntentionCooperation = () => {
    if (data.value) {
      navigateTo({
        name: 'intentionCooperation',
        options: {
          id: data.value?.id,
          type: 'list',
          boType: data.value?.boType,
          title: data.value?.title,
        },
      });
    }
  };
  const useUser = useUserStore();
  /** 去提交意向 */
  async function handleApplyCooperation() {
    await useUser.validatePerfectionInfo();
    let applyType = data.value?.applyType || '';
    if (applyType?.length > 1) applyType = applyType.split(',')[0];
    navigateTo({
      name: 'applyDirectCooperation',
      options: {
        id: data.value?.id!,
        type: Number(applyType) as unknown as ApplicationTypeEnum,
        shareKey: routeOptions.value?.shareKey,
      },
    });
  }

  onShareTimeline(() => ({}));
  onPullDownRefresh(() => {
    getData();
  });
</script>

<style lang="scss" scoped>
  .footer-placeholder {
    height: 188rpx;
  }

  .footer {
    width: 100%;
    height: 128rpx;
    position: fixed;
    left: 0;
    bottom: 0;
    background-color: #fff;
    box-shadow: 0px 4rpx 24rpx 0px rgba(150, 151, 153, 0.16);
  }

  .phoneCall-info {
    box-sizing: border-box;
    width: 622rpx;
    border-radius: 32rpx;
    background-color: #fff;
    padding: 48rpx 48rpx 32rpx 48rpx;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: space-around;
    .title {
      color: #333;
      text-align: center;
      font-size: 32rpx;
      font-weight: 400;
      line-height: 48rpx;
      font-weight: bold;
    }
    .desc {
      color: #333;
      text-align: center;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 40rpx;
      margin: 24rpx 0 32rpx 0;
    }
    .phoneCall-info_item_box {
      width: 100%;
      max-height: 400rpx;
      overflow-y: scroll;

      .phoneCall-info_item {
        width: 100%;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 32rpx;
        color: #333;
        padding: 24rpx 20rpx;
        background-color: #f7f8fa;
        margin-top: 20rpx;
        border-radius: 16rpx;
      }
      .phoneCall-info_phone {
        color: #4a75ff;
      }
    }

    .btn {
      margin-top: 32rpx;
      box-sizing: border-box;
      display: flex;
      width: 100%;
      height: 72rpx;
      padding: 8px 0px;
      justify-content: center;
      align-items: center;
      border-radius: 32rpx;
      background: #2878ff;
      color: #fff;
      font-size: 28rpx;
    }
  }
</style>
